package com.mapproject.industrymap.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mapproject.industrymap.entity.ChildGeomEntity;
import com.mapproject.industrymap.entity.SysUploadFileEntity;
import com.mapproject.industrymap.mapper.FoodassetsChildInfoMapper;
import com.mapproject.industrymap.mapper.SysUploadFileMapper;
import com.mapproject.industrymap.service.SysUploadFileService;
import com.mapproject.industrymap.service.ShpTransforPgService;
import com.mapproject.industrymap.utils.CopyFileUtils;
import com.mapproject.industrymap.utils.DataPgdump;
import com.mapproject.industrymap.utils.ReturnValue;
import org.apache.logging.log4j.message.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import com.mapproject.industrymap.utils.DataItemShapefile;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
public class SysUploadFileServiceImpl extends ServiceImpl<SysUploadFileMapper, SysUploadFileEntity>  implements SysUploadFileService {
    @Value("${file.uploadFolder}")
    private String uploadFolder;
    @Value("${file.projectFileDir}")
    private String projectFileDir;
    @Autowired
    SysUploadFileMapper sysUploadFileMapper;
    @Autowired
    FoodassetsChildInfoMapper foodassetsChildInfoMapper;
    @Autowired
    ShpTransforPgService shpTransforPgService;

    public ReturnValue uploadfile(MultipartFile multipartFile,String torowguid) {
        String uploadPath=projectFileDir;
        String fileName = multipartFile.getOriginalFilename();  // 文件名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        String filePath = uploadFolder+uploadPath;//这个path就是你要存在服务器上的
        String rowguid = UUID.randomUUID().toString(); // 主键uuid
        String fileNameNew = UUID.randomUUID() +suffixName; // 新文件名
        String systemdate=getsystemdate();
        File dest = new File(filePath + fileNameNew);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            String serverfilepath=uploadPath+fileNameNew;
            multipartFile.transferTo(dest);
            SysUploadFileEntity fileInfo=SysUploadFileEntity.builder()
                    .rowguid(rowguid)
                    .filename(fileName)
                    .serverfileurl(serverfilepath)
                    .inserttime(systemdate)
                    .filetype(suffixName)
                    .inserttime(systemdate)
                    .torowguid(torowguid)
                    .status("1")
                    .build();
            boolean result =saveOrUpdate(fileInfo);
            if (result){
                String key = fileInfo.getRowguid();
                SysUploadFileEntity newfileinfo=getById(key);
                return new ReturnValue(200,"上传文件成功",newfileinfo);
            }else {
                return new ReturnValue(500,"上传文件失败");
            }
        } catch (IOException e) {
            e.printStackTrace();
            return new ReturnValue(500,"上传文件失败");
        }

    }

    public ReturnValue uploadshpfile(MultipartFile multipartFile,String torowguid) {
        String uploadPath=projectFileDir;
        String fileName = multipartFile.getOriginalFilename();  // 文件名
        //String suffixName = fileName.substring(fileName.lastIndexOf("."));
        String fileNametitle=fileName.substring(0,fileName.lastIndexOf("."));
        String filePath = uploadFolder+uploadPath;//这个path就是你要存在服务器上的
        //String rowguid = UUID.randomUUID().toString(); // 主键uuid
        String filePathNew = filePath+fileNametitle+"/"; // 新文件夹名
        //String systemdate=getsystemdate();
        File dest = new File(filePathNew + fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            multipartFile.transferTo(dest);
            //存入PG库
            /*String path =
            String result = shpTransforPgService.insertShpData(String path);*/
            //List<String> dataret= unZipFile.batchadd(path);



            /*String result="";
            String path =filePath+fileNametitle;
            File file = new File(path);
            File[] files = file.listFiles();
            for (File f : files){
                String suffixName = f.getName().substring(f.getName().lastIndexOf(".")+1);
                if(suffixName.equals("shp")){
                    DataItemShapefile dataItemShapefile=new DataItemShapefile();
                    System.out.println(f.getPath());
                    result = dataItemShapefile.readSHP(f.getPath());
                    System.out.println(result);
                    break;
                }
            }*/

            if (dest!=null){
                return new ReturnValue(200,"上传文件成功");
            }else {
                return new ReturnValue(500,"上传文件失败");
            }
        } catch (IOException e) {
            e.printStackTrace();
            return new ReturnValue(500,"上传文件失败");
        }

    }

    public ReturnValue uploaddxf(MultipartFile multipartFile,String torowguid) {
        String uploadPath=projectFileDir;
        String fileName = multipartFile.getOriginalFilename();  // 文件名
        String fileNametitle=fileName.substring(0,fileName.lastIndexOf("."));
        String filePath = uploadFolder+uploadPath;//这个path就是你要存在服务器上的
        String filePathNew = filePath+fileNametitle+"/"; // 新文件夹名
        File dest = new File(filePathNew + fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            multipartFile.transferTo(dest);

            if (dest!=null){
                return new ReturnValue(200,"上传文件成功");
            }else {
                return new ReturnValue(500,"上传文件失败");
            }
        } catch (IOException e) {
            e.printStackTrace();
            return new ReturnValue(500,"上传文件失败");
        }

    }


    public ReturnValue queryInfo(String torowguid){
        QueryWrapper<SysUploadFileEntity> queryWrapper=new QueryWrapper<>();
        queryWrapper
                .eq("torowguid",torowguid)
                .eq("status","1");
        List<Map<String, Object>> maps = sysUploadFileMapper.selectMaps(queryWrapper);
        return new ReturnValue(200,"查询结果",maps);

    }
    public String getsystemdate(){
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd kk:mm:ss ");
        return sdf.format(d);
    }
    public ReturnValue exportfile()throws IOException{
        String result=foodassetsChildInfoMapper.queryfilegroup();
        JSONArray jsonArray =  JSONObject.parseArray(result);
        try {
            for(int i = 0; i < jsonArray.size(); i++) {
                JSONObject obj = jsonArray.getJSONObject(i);
                String publicorperson=(String) obj.get("publicorperson");
                String topdir=(String) obj.get("assetsname");
                String lastdir="未填";
                JSONArray fileinfo=(JSONArray) obj.get("fileinfo");
                if(publicorperson.equals("1")){
                    lastdir=(String) obj.get("estatename");
                }else{
                    lastdir=(String) obj.get("buildingname");
                }
                String fulldir="F:\\outputfile\\"+topdir+"\\"+lastdir;
                mkdir(fulldir);
                if (fileinfo==null||fileinfo.size()<1){
                    continue;
                }
                copyfile(fulldir,fileinfo);
            }
            return new ReturnValue(200,"导出文件成功");
        }catch (Exception ex){
            return new ReturnValue(200,"导出文件失败",ex);
        }

    }

    public void mkdir(String fulldir){
        File file=new File(fulldir);
        if (file.exists() && file.isDirectory()) {
            return ;
        }
        if (file.exists()) {
            file.delete();
            file.mkdirs();
        } else {
            file.mkdirs();
        }
    }
    public void copyfile(String fulldir,JSONArray fileArray) throws IOException {

        for(int i = 0; i < fileArray.size(); i++) {
            JSONObject obj = fileArray.getJSONObject(i);
            String filedir=(String)obj.get("serverfileurl");
            String strdir = filedir.substring(0, filedir.indexOf("/"));
            String strfile = filedir.substring( filedir.indexOf("/")+1);
            File source = new File(uploadFolder+strdir+"\\"+strfile);
            File dest = new File(fulldir+"\\"+strfile);
            CopyFileUtils copyFileUtils=new CopyFileUtils();

            int result= copyFileUtils.copyfile(source,dest);
        }
    }

    public ReturnValue deletefile(String rowguid){
        SysUploadFileEntity sysUploadFileEntity=new SysUploadFileEntity();
        sysUploadFileEntity.setStatus("0");
        try{
            UpdateWrapper<SysUploadFileEntity> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("rowguid",rowguid);
            int ret=  sysUploadFileMapper.update(sysUploadFileEntity,updateWrapper);
            return  new ReturnValue(200,"删除成功",ret);

        }catch (Exception ex){
            return  new ReturnValue(500,"删除失败");
        }

    }
    }

